import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../player/player.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:hairen_app/server/server.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class CategoryPage extends StatefulWidget {
  final String cateName;

  CategoryPage({this.cateName}) : super();

  @override
  State<StatefulWidget> createState() => new CategoryPageState();
}

class CategoryPageState extends State<CategoryPage>
    with SingleTickerProviderStateMixin {

  ScrollController _scrollController = new ScrollController();




  List<String> dianying = [
    "全部类型",
    "动作片",
    "爱情片",
    "科幻片",
    "喜剧片",
    "战争片",
    "恐怖片",
    "剧情片",
    "记录片"
  ];
  List<String> dianshiju = [
    "全部类型",
    "国产剧",
    "港台剧",
    "日韩剧",
    "欧美剧",
  ];
  List<String> zhongyi = [
    "综艺",
  ];
  List<String> dongman = [
    "动漫",
  ];
  List<String> moveTime = [
    "2018",
  ];
  List<String> moveAreas = [
    "不限地区",
    "大陆",
    "美国",
    "香港",
    "台湾",
    "法国",
    "德国",
    "英国",
    "其他",

  ];
  List<String> moveYear=[
      "默认年代",
      "2018",
      "2017",
      "2016",
      "2015",
      "2014",
      "2013",
      "2012",
      "2011",
      "00年代",
      "90年代",
      "80年代",
      "70年代",
      "其他",
  ];


  List<String> moves = [];

  Map<String, int> pages = {
    'total': 0,
    'per_page': 0,
    'current_page': 0,
    'last_page': 0,
  };
  List<Widget> cateList = <Widget>[]; //分类
  List cateRows = []; //数据
  bool iscateRows = false; //是否右数据
  bool isOvrecateRows = false; //是否全部加载完

  int Index = 0;
  bool isLoading = false;

  //判断list 滑动方向
  List<double> 	direction=[];
  bool 	slideDirection=true;

  //现实筛选
  bool isUpSlide=false; //往上
  double isUpSlideCacheHeight=0.0; //往上缓存距离
  bool isDowSlide=false; //向下
  double isDowSlideCacheHeight=0.0; //向下缓存距离


  //条件
  bool iswherePlay=true;
  bool iswhereTime=true;
  Map<String,String> where={
    'category':'',
    'order_field':'',
    'order_by':'',
    'area':'',
    'show':'',
  };
  @override
  initState() {
    super.initState();
    if (widget.cateName == "电影") {
      moves = dianying;
    }
    if (widget.cateName == "电视剧") {
      moves = dianshiju;
    }
    if (widget.cateName == "综艺") {
      moves = zhongyi;
    }
    if (widget.cateName == "动漫") {
      moves = dongman;
    }
    if (widget.cateName == "电视直播") {
      moves = [];
    }
    clearRows();
    //默认数据
    getRows(buidWhere("category",moves.join(",")));

    _scrollController.addListener((){

      //监听加载更多
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
          if (!isLoading) {
            this.isLoading = true;
            getLoadMore();
          }
      }

      setState(() {
        direction.add(_scrollController.offset);
        if(direction.length>2){
          if(direction[0]<direction[1]){
//            print("下滑动");
            isUpSlide=true;
            //

            slideDirection=true;
          }else{
            isDowSlide=true;
//            print("上滑动");
            slideDirection=false;
          }
          direction.removeAt(0);
        }


        //下滑隐藏搜索栏
        if(_scrollController.offset.ceil()<=max_filter_height_translation.abs().ceil()&&slideDirection){

          filter_height_translation=-_scrollController.offset;
          isDowSlide=false;

        }
//        &&isTopSlide
        if(_scrollController.offset>140&&slideDirection){ //超过140以后 如果没有隐藏搜索栏 则隐藏搜索栏
          filter_height_translation=max_filter_height_translation;
//          print(isDowSlideCacheHeight);
//          if(isDowSlide){
//            isDowSlide=false;
//            isDowSlideCacheHeight=_scrollController.offset+135.0;
//          }
//
//          if(_scrollController.offset>isUpSlideCacheHeight){
////            print(-(_scrollController.offset-isUpSlideCacheHeight));
//            print("展开：${-(_scrollController.offset-isUpSlideCacheHeight)}");
//            filter_height_translation=-(_scrollController.offset-isUpSlideCacheHeight);
//          }


        }
        if(!slideDirection){ //向下滑动展开搜索栏
          isDowSlideCacheHeight=0.0;
//          filter_height_translation=0.0;
          if(isUpSlide){
            isUpSlide=false;
             isUpSlideCacheHeight=_scrollController.offset-135.0;
          }

          if(_scrollController.offset>isUpSlideCacheHeight){
//            print(-(_scrollController.offset-isUpSlideCacheHeight));
//            print("展开：${-(_scrollController.offset-isUpSlideCacheHeight)}");
            filter_height_translation=-(_scrollController.offset-isUpSlideCacheHeight);
          }else{
            filter_height_translation=0.0;
          }


        }
      });
    });


  }
  //运行动画

  void clearRows() {
    setState(() {
      cateRows=[];
    });
  }

  Map<String,String> buidWhere(String key,String val){
     where[key]=val;

     where['page']='1';
     return where;

  }

  getRows(Map<String, String> data) {
    print(data);
    clearRows();
    Server.getMovesRows(data: data).then((ret) {
      setState(() {
        var data = ret['data']['data'];

        pages['total'] = ret['data']['total'];

        if(pages['total']==0){
          iscateRows=true;
        }
//        iscateRows
        pages['per_page'] = ret['data']['per_page'];
        pages['current_page'] = ret['data']['current_page'];
        pages['last_page'] = ret['data']['last_page'];
        cateRows = data;
      });
    });
  }

  void getLoadMore() {
    Map<String, String> data;
      data = where;
      int page = pages['current_page'];
      int currPage = page + 1;
      if (currPage >= pages['total']) {
        //展示完毕
        isOvrecateRows=true;
      } else {
        data["page"] = currPage.toString();
        Server.getMovesRows(data: data).then((ret) {
            var data = ret['data']['data'];
            setState(() {
//           print(cateRows[Index]);
            pages['total'] = ret['data']['total'];
            pages['per_page'] = ret['data']['per_page'];
            pages['current_page'] = ret['data']['current_page'];
            pages['last_page'] = ret['data']['last_page'];
            cateRows.addAll(data);
            isLoading=false;//加载完毕
          });
        });
      }
  }

  @override
  dispose() {
    super.dispose();
    _scrollController.dispose();

  }



  //默认筛选偏移高度
  double filter_height_translation = -0.0;
  double max_filter_height_translation = -135.0;
  double viewHeight = 0.0;

  @override
  Widget build(BuildContext context) {
    viewHeight = MediaQuery.of(context).size.height -
        MediaQuery.of(context).padding.top -
        180 -
        56-filter_height_translation;
    return new Scaffold(
        backgroundColor: Color.fromRGBO(234, 234, 234, 1.0),
        appBar: new AppBar(
          title: new Align(
            alignment: Alignment.centerLeft,
            child: new Text(
              widget.cateName,
              style: new TextStyle(
                color: Colors.white,
              ),
            ),
          ),
        ),
        body: new Stack(
          children: <Widget>[
            new Positioned(
              top: 0.0,
              left: 0.0,
              right: 0.0,
              child: new Container(
                transform: Matrix4.translationValues(
                    0.0, filter_height_translation, 0.0),
                height: 180.0,
                decoration: new BoxDecoration(
                  color: Color.fromRGBO(255, 255, 255, 1.0),
                  boxShadow: <BoxShadow>[
                    new BoxShadow(
                      color: Color.fromRGBO(179, 179, 177, 0.3),
                      blurRadius: 20.0,
                      spreadRadius: 1.0,
                      offset: Offset(1.0, 10.0),
                    ),
                  ],
                ),
                child: new Column(
                  children: <Widget>[
                    new Container(
                      alignment:Alignment.centerLeft,
                      height: 45.0,
                      child:  new Container(
                        height: 30.0,
                        child:new ListView(
                        scrollDirection: Axis.horizontal,
                        children: [
                         new  FlatButton(onPressed: (){

                           getRows(buidWhere("order_field","m.update"));
                           getRows(buidWhere("order_by",where['order_by']=="desc"?"asc":"desc"));
                           setState(() {
                             iswhereTime=where['order_by']=="desc"?true:false;
                           });
                         }, child: new Row(children: <Widget>[new Text("最新上映"),iswhereTime?new Icon(Icons.vertical_align_top):new Icon(Icons.vertical_align_bottom)],)),
                         new  FlatButton(onPressed: (){
                           getRows(buidWhere("order_field","h.click"));
                           getRows(buidWhere("order_by",where['order_by']=="desc"?"asc":"desc"));
                           setState(() {
                             iswherePlay=where['order_by']=="desc"?true:false;
                           });
                         }, child: new Row(children: <Widget>[new Text("最多播放"),iswherePlay?new Icon(Icons.vertical_align_top):new Icon(Icons.vertical_align_bottom)],)),
                        ],
                      )
                      ),
                    ),
                    new Container(
                      alignment:Alignment.centerLeft,
                      height: 45.0,
                      child: new Container(
                        height: 30.0,
                        child:new ListView(
                        scrollDirection: Axis.horizontal,
                        children: moves.map((item){
                          return FlatButton(onPressed: (){
                            getRows(buidWhere("category",item=="全部类型"?moves.join(","):item));
                          }, child: new Text(item,style: new TextStyle(color: where['category']==item||where['category'].toString().split(',')[0]==item?Colors.white:null),),color: where['category']==item||where['category'].toString().split(',')[0]==item?Theme.of(context).backgroundColor:null,);
                        }).toList(),
                      )),
                    ),
                    new Container(
                      height: 45.0,
                      alignment:Alignment.centerLeft,
                      child: new Container(
                        height: 30.0,
                        child:new ListView(
                        scrollDirection: Axis.horizontal,
                        children: moveAreas.map((item){
                          String isNull=where['area']==""?"不限地区":"";
                          return FlatButton(onPressed: (){
                            getRows(buidWhere("area",item=="不限地区"?"":item));
                          }, child:  new Text(item,style: new TextStyle(color: where['area']==item||isNull==item?Colors.white:null),),color: where['area']==item||isNull==item?Theme.of(context).backgroundColor:null,);
                          ;
                        }).toList(),
                      )),
                    ),
                    new Container(
                      alignment:Alignment.centerLeft,
                      height: 45.0,
                      child: new Container(
                         height: 30.0,
                        child: new ListView(
                          scrollDirection: Axis.horizontal,
                          children: moveYear.map((item){
                            String issNull=where['show']==""?"默认年代":"";
                            return FlatButton(onPressed: (){
                              getRows(buidWhere("show",item=="默认年代"?"":item));
                            }, child: new Text(item,style: new TextStyle(color: where['show']==item||issNull==item?Colors.white:null),),color: where['show']==item||issNull==item?Theme.of(context).backgroundColor:null,);
                          }).toList(),
                        ),
                      ),
                    ),
                  ],
                ),
                width: MediaQuery.of(context).size.width,
              ),
            ),
            new Positioned(
              top: 185.0+filter_height_translation,
              left: 0.0,
              right: 0.0,
              child: cateRows.length==0?(iscateRows?new Align(child: new Text("暂无数据"),):new Container(
                height: 100.0,
                child: new SpinKitWave(
                  color: Color.fromRGBO(251, 114, 153, 1.0),
                  size: 30.0,
                ),
              )):new Container(
                padding: EdgeInsets.only(left: 0.0,right: 0.0),
                height: viewHeight-12.0,
                child: new StaggeredGridView.countBuilder(
                  controller: _scrollController,
                  crossAxisCount: 3,
                  itemCount: cateRows.length,
                  itemBuilder: (BuildContext context, int index) =>  new InkWell(child: new Card(
                    margin: EdgeInsets.all(0.0),
//                    color:Colors.white.withOpacity(0.0),
                    child: new Stack(
                      alignment:Alignment.center,
                      children: <Widget>[
                        new ConstrainedBox(constraints: new BoxConstraints.expand(),child: new Image.network(cateRows[index]['logo'],fit: BoxFit.cover,),),
                        new Positioned(
                          bottom: 0.0,
                          left: 0.0,
                          right: 0.0,
                          child: new Container(
                            height: 45.0,
                            color: Colors.black.withOpacity(0.6),
                            child:  new Padding(
                              padding: const EdgeInsets.all(4.0),
                              child: new Column(
                                children: <Widget>[
                                  new Expanded(child: new Text(
                                    "${cateRows[index]['title'].toString().substring(0,cateRows[index]['title'].toString().length>9?8:cateRows[index]['title'].toString().length)}",
                                    style: const TextStyle(color: Colors.white,fontWeight: FontWeight.bold),
                                  ),),
                                  new SizedBox(height: 5.0,),
                                  new Expanded(
                                    child: new Text(
                                      "${cateRows[index]['title_type'].toString().substring(0,cateRows[index]['title_type'].toString().length>15?14:cateRows[index]['title_type'].toString().length)}",
                                      style: const TextStyle(color: Colors.white,fontSize: 11.0),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                   onTap: (){
                     Navigator.of(context).push(
                         new CupertinoPageRoute(builder: (context)=>new PlayerPage(mid:int.parse(cateRows[index]['id'])))
                     );
                   },
                  ),
                  staggeredTileBuilder: (int index){
                  return new StaggeredTile.count(1,1.2)
                  ;},
                  mainAxisSpacing: 15.0,
                  crossAxisSpacing: 5.0,
                ),
                width: MediaQuery.of(context).size.width,
              ),
            ),
            new Positioned(
              bottom: 0.0,
              left: 0.0,
              right: 0.0,
              child:  new Offstage(
                offstage: !isLoading,
                child:pages['current_page']==pages['last_page']?new Align(child: new Text('加载完毕！'),):new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new CupertinoActivityIndicator(),
                    new Text("努力加载中")
                  ],
                ),
              ),
            )
          ],
        ));
  }
}

